const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()

const views = require('koa-views')
const co = require('co')
const convert = require('koa-convert')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')

const config = require('./config')
const routes = require('./routes')
// 解决跨域
const cors = require('koa-cors');

const port = process.env.PORT || config.port

// error handler
onerror(app)

// middlewares
app.use(bodyparser())
  .use(json())
  .use(logger())
  .use(require('koa-static')(__dirname + '/public'))
  .use(views(path.join(__dirname, '/views'), {
    options: {settings: {views: path.join(__dirname, 'views')}},
    map: {'njk': 'nunjucks'},
    extension: 'njk'
  }))
  .use(cors()) 
  .use(router.routes())
  .use(router.allowedMethods())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - $ms`)
})
// 联想查询
router.get('/data/search', (ctx) => {
  const { keyword } = ctx.request.query
  // 定义数据
  const foods = [
    { 
        id:1,
        name:'时蔬过桥米线',
        available:true
    },
    { 
        id:2,
        name:'秀才过桥米线',
        available:false
    },
    { 
        id:3,
        name:'肥牛过桥米线',
        available:true
    },
    { 
        id:4,
        name:'甜酒汤圆',
        available:true
    }
  ]
  const res =foods.map((item) => {
     if (item.name.includes(keyword)) {
        return item.name
      }
  })
  ctx.response.body = res
   
})
// 用户名查重
router.get('/name', (ctx) => {
  const {name,password} = ctx.request.query;
  const nameArray = ['lucy', 'tomy', 'isen', 'lily']
  let data = {
    success:'注册成功'
  }
  nameArray.forEach(item => {
    if (item == name) {
      data = {
         success:'用户名已存在'
       }
     }
  })
  ctx.response.body = data;
})



router.get('/', async (ctx, next) => {
  // ctx.body = 'Hello World'
  ctx.state = {
    title: 'Koa2'
  }
  await ctx.render('index', ctx.state)
})

routes(router)
app.on('error', function(err, ctx) {
  console.log(err)
  logger.error('server error', err, ctx)
})

module.exports = app.listen(config.port, () => {
  console.log(`Listening on http://localhost:${config.port}`)
})

